/**
 * @file common_thread_monitor.h
 * @author Jio (hedajun@hzdusun.com)
 * @brief 
 * @version 0.1
 * @date 2023-12-08
 * 
 * @copyright Copyright (c) 2023
 * 
 */
#ifndef __COMMON_THREAD_MONITOR_H
#define __COMMON_THREAD_MONITOR_H

#include <stdint.h>
#include <sys/time.h>
#include "common_types.h"

#ifdef __cplusplus
extern "C"{
#endif


#define MAX_THREAD_MONITOR_COUNT                          20
#define THREAD_MONITOR_SCHEDULE_TIMEOUT_1MIN              (60*1000000L)    // 1min
#define THREAD_MONITOR_SCHEDULE_TIMEOUT_5MIN              (5*60*1000000L)    // 5min


/**
 * @brief 用于仿真测试模拟应用离线
 * 
 */
typedef enum
{
    TM_SIM_NONE = 0,
    TM_SIM_MQTT_ONLINE = 1,
    TM_SIM_MQTT_OFFLINE = 2,
}thread_monitor_sim_t;

typedef struct 
{
    RB_INT8 name[25];
    RB_UINT64 schedule_times;            //调度次数
    RB_UINT64 work_time_ticks;           //工作占用时间片
    struct timespec  last_active_time;      //上次被调度到的时间
    RB_UINT64 watch_timeout_us;
    RB_BOOL set_block;
}__attribute__((packed)) thread_monitor_context_t;


typedef RB_VOID (*thread_catch_abort_callback_t) (thread_monitor_context_t*, const RB_INT8*);
typedef RB_VOID  (*thread_monitor_iter_callback_t) (thread_monitor_context_t*);
/**
 * @brief 启动线程监控
 * 
 * @return RB_INT32 
 */
RB_INT32 thread_monitor_init(thread_catch_abort_callback_t on_abort);

/**
 * @brief 创建线程监控context
 * 
 * @param name 
 * @return thread_monitor_context_t* 
 */
thread_monitor_context_t* thread_monitor_create(const RB_INT8* name);

/**
 * @brief 销毁线程监控context
 * 
 * @param name 
 * @return thread_monitor_context_t* 
 */
RB_VOID thread_monitor_destory(thread_monitor_context_t* context);

/**
 * @brief 将contetx加入线程监控
 * 
 * @param contex 
 * @return RB_INT32 
 */
RB_INT32 thread_monitor_catch(thread_monitor_context_t* context);


/**
 * @brief 激活线程，配合thread_monitor_context_update使用，统计线程激活时间
 * 
 * @param context 
 */
RB_VOID thread_monitor_context_active(thread_monitor_context_t* context);

/**
 * @brief 刷新context
 * 
 * @param context 
 */
RB_VOID thread_monitor_context_update(thread_monitor_context_t* context);


/**
 * @brief 迭代所有监控的context
 * 
 */
RB_INT32 thread_monitor_iter(thread_monitor_iter_callback_t cb);


RB_INT32 thread_monitor_block(RB_INT32 block_index, RB_BOOL block);

RB_VOID thread_monitor_timeout_disable(thread_monitor_context_t* context);
RB_VOID thread_monitor_timeout_set(thread_monitor_context_t* context, RB_UINT64 timeout);
#ifdef __cplusplus
}
#endif

#endif